package com.qf.sy2103.fmmall.api.controller;


import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.endpoint.EndpointUtils;
import com.qf.sy2103.fmmall.beans.vo.UserRegistVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/test")
public class TestController {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    private EurekaClient eurekaClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/eureka-get")
    public String testEurekaClientGet() {
        //1. 通过eurekaClient获取到SEARCH服务的信息
        InstanceInfo info = eurekaClient.getNextServerFromEureka("FMALLUSER", false);

        //2. 获取到访问的地址
        String url = info.getHomePageUrl();
        System.out.println(url);

        //3. 通过restTemplate访问
        String result = restTemplate.getForObject(url + "/useraddr/list?userId=1", String.class);

        //4. 返回
        return result;
    }

    @RequestMapping("/eureka-post")
    public String testEurekaClientPost() {
        //1. 通过eurekaClient获取到SEARCH服务的信息
        InstanceInfo info = eurekaClient.getNextServerFromEureka("FMALLUSER", false);

        //2. 获取到访问的地址
        String url = info.getHomePageUrl();
        System.out.println(url);

        final UserRegistVo userRegistVo = new UserRegistVo("testA", "123456", "123456");

        //3. 通过restTemplate访问
        String result = restTemplate.postForObject(url + "/user/regist", userRegistVo, String.class);

        //4. 返回
        return result;
    }


    @RequestMapping("/discovery-get")
    public String testDiscoveryClientGet() {
        final List<ServiceInstance> list = discoveryClient.getInstances("FMALLUSER");
        if (list != null && list.size() > 0) {
            ServiceInstance info = list.get(0);
            //2. 获取到访问的地址
            final URI uri = info.getUri();
            System.out.println(uri);

            //3. 通过restTemplate访问
            String result = restTemplate.getForObject(uri.toString() + "/useraddr/list?userId=1", String.class);

            //4. 返回
            return result;
        }
        return null;
    }
}
